package com.eeepay.eeepay_v2.activity;

import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.adapter.AddProfitAdapter2;
import com.eeepay.eeepay_v2.api.AgentServicesRequestAPI;
import com.eeepay.eeepay_v2.app.MyApplication;
import com.eeepay.eeepay_v2.model.AgentAddInfo;
import com.eeepay.eeepay_v2.model.AgentProfitInfo;
import com.eeepay.eeepay_v2.model.UserInfo;
import com.eeepay.eeepay_v2.util.AllUtils;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.eeepay_v2.util.SPUtils;
import com.eeepay.v2_library.ui.ABBaseActivity;
import com.eeepay.v2_library.view.TitleBar;

import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.eeepay.api.grpc.nano.AddAgentProto;
import cn.eeepay.api.grpc.nano.AddAgentServiceGrpc;
import cn.eeepay.api.grpc.nano.MerchantSearchProto;
import io.grpc.ManagedChannel;

/**
 * Created by Ching on 2017/2/28.
 * 新增代理商第二步 --- 分润设置
 */

public class AgentAddStep4 extends ABBaseActivity implements View.OnClickListener {

    private final String TAG = AgentAddStep4.class.getSimpleName();
    private TitleBar titleBar;
    private ListView listView;
//    private AddProfitAdapter adapter;
    private AddProfitAdapter2 adapter2;
    private Button nextBtn;

    private List<AgentProfitInfo> list;
    private AgentAddInfo addInfo;
    private String[] bpId;//勾选的产品业务的 bpid 数组

    private AddAgentProto.ShareData[] shareDatas;//单点击完成；需要自己组装；填写的分润设置内容
    @Override
    protected int getLayoutId() {
        return R.layout.activity_agent_add_step_3;
    }

    @Override
    protected void initWidget() {
        titleBar = getViewById(R.id.titleBar);
        titleBar.setTiteTextView("新增代理商(分润设置)");
        listView = getViewById(R.id.lv_add_agent);
        listView.setDividerHeight(30);
        listView.setItemsCanFocus(true);
        listView.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
        listView.requestFocus();
        nextBtn = getViewById(R.id.btn_next);
        //add by zhuangzeqin 2017年4月24日14:15:37 最后一步；变成完成；由于公用一个页面3
        nextBtn.setText(getResources().getText(R.string.str_finish));
        list = SPUtils.getList(Constant.KEY.AGENT_ADD_LIST);
        SPUtils.removeList(list.size(), Constant.KEY.AGENT_ADD_LIST);
        //add by zhuangzeqin 2017年6月2日09:12:18  当不为空的时候；开始组装pbid 数组 存放到数组里后续用于网络请求
        if (list != null && list.size() > 0) {
            bpId = new String[list.size()];
            for (int i=0;i<list.size();i++)
            {
                AgentProfitInfo agentProfitInfo =list.get(i);
                bpId[i] =  agentProfitInfo.getBpId();//存放到数组里
            }
            requestServiceInfo();
        }
    }

    /**
     * 获取分润服务信息
     */
    private void requestServiceInfo() {
        showProgressDialog();
        AgentServicesRequestAPI agentServicesRequestAPI = new AgentServicesRequestAPI(bpId, UserInfo.getUserInfo2SP().getAgentNo());
        agentServicesRequestAPI.setResultCallBack(new AgentServicesRequestAPI.ResultCallBack() {
            @Override
            public void onFail(String msg) {//失败
                dismissProgressDialog();
                showToast(msg);
            }

            @Override
            public void onSucess(List<MerchantSearchProto.AgentServicesInfo> infoList) {//成功
                dismissProgressDialog();
                adapter2 = new AddProfitAdapter2(mContext,infoList);
                adapter2.setList(infoList);
                listView.setAdapter(adapter2);//填充数据
            }
        });
        agentServicesRequestAPI.getAdentServicesInfo();//开始请求
    }

    @Override
    protected void eventOnClick() {
        nextBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        List<MerchantSearchProto.AgentServicesInfo> infoList =adapter2.getDatas();
        for (MerchantSearchProto.AgentServicesInfo agentServicesInfo : infoList) {
            if (TextUtils.isEmpty(agentServicesInfo.profit)) {
                showToast("请完成 " + agentServicesInfo.bpName + " 的分润设置填写");
                return;
            }
        }
//        string cardType 			= 1;		// 银行卡种类:0-不限，1-只信用卡，2-只储蓄卡
//        string holidaysMark 		= 2;		// 节假日标志:0-不限，1-只工作日，2-只节假日
//        string profitType			= 3;		// 分润类型, 固定传 5
//        string serviceId 			= 4;		// 服务id
//        string shareProfitPercent 	= 5;		//代理商固定分润百分比 固定传100
//        string costRateType 		= 6;		// 	代理商成本费率类型:1-每笔固定金额(serviceType = 10000 or serviceType=10001)，2-扣率，
//        string cost					= 7;		// 固定金额或固定比率
//        string serviceTypeName    		= 8;		// 服务类型名称 bpName + "-" + serviceTypeName
        shareDatas = new AddAgentProto.ShareData[infoList.size()];
        for (int i = 0; i < infoList.size(); i++) {
            MerchantSearchProto.AgentServicesInfo agentServicesInfo = infoList.get(i);
            AddAgentProto.ShareData shareData = new AddAgentProto.ShareData();
            shareData.cardType = agentServicesInfo.cardType;// 银行卡种类:0-不限，1-只信用卡，2-只储蓄卡
            shareData.holidaysMark =agentServicesInfo.holidaysMark;// 节假日标志:0-不限，1-只工作日，2-只节假日
            shareData.profitType = "5";// 分润类型, 固定传 5
            shareData.serviceId = agentServicesInfo.serviceId;// 服务id
            shareData.shareProfitPercent = "100";//代理商固定分润百分比 固定传100
            // 	代理商成本费率类型:1-每笔固定金额(serviceType = 10000 or serviceType=10001)，2-扣率，
            if (agentServicesInfo.serviceType.equals("10000") || agentServicesInfo.serviceType.equals("10001") )
                shareData.costRateType = "1";
            else
                shareData.costRateType = "2";
            shareData.cost = agentServicesInfo.profit;//设置的固定金额还是固定比率,都把值存放到cost里
            //服务类型名称
            String serviceTypeName = String.format("%s(%s)",agentServicesInfo.bpName,agentServicesInfo.serviceTypeName);
            shareData.serviceTypeName = serviceTypeName;
            shareDatas[i]= shareData;//组装分润设置内容
        }
        //开始发送请求
        sendHttpRequest(0);
    }

    @Override
    protected void sendHttpRequest(int taskId) {
        showProgressDialog();
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT, taskId, new GrpcUtils.AsyncTaskListener() {
            //        GrpcUtils.getInstance().doGrpcTask("192.168.4.4", "8090", taskId, new GrpcUtils.AsyncTaskListener() {
            @Override
            public Object doInBack(ManagedChannel channel, int taskId) {
                AddAgentServiceGrpc.AddAgentServiceBlockingStub stub = AddAgentServiceGrpc
                        .newBlockingStub(channel).withDeadlineAfter(60, TimeUnit.SECONDS);
                AddAgentProto.ReqAgentInfo req = new AddAgentProto.ReqAgentInfo();
                addInfo = SPUtils.getAgentAddInfo();
                req.agentNo = UserInfo.getUserInfo2SP().getAgentNo();//代理商ID
                req.agentName = addInfo.getAgentName();//代理商名称
                req.linkName = addInfo.getUserName();//联系人
                req.email = addInfo.getEmail();//邮箱
                req.mobilephone = addInfo.getPhone();//手机号
                req.province = addInfo.getProvince();//省
                req.city = addInfo.getCity();//市
                req.area = addInfo.getArea();//区
                //结算信息
                req.accountType = addInfo.getAccountType();//账户类型  1：对公，2：对私
                req.accountName = addInfo.getAccountName();//开户名
                req.accountNo = addInfo.getAccountNo();//开户账户
                req.bankName = addInfo.getBankName();//开户行全称
                if (!TextUtils.isEmpty(addInfo.getCnapsNo())) {//联行行号
                    req.cnapsNo = addInfo.getCnapsNo();
                } else {
                    req.cnapsNo = "";
                }
                req.accountProvince = addInfo.getAccount_province();//开户行地区：省
                req.accountCity = addInfo.getAccount_city();//开户行地区：市
                req.subBank = addInfo.getZh();//支行
                req.saleName = addInfo.getSaleName();//销售名称

                req.userId = UserInfo.getUserInfo2SP().getUserNo();//userid
                req.agentArea = addInfo.getAddress();//代理区域
                //组织id
                req.teamId = MyApplication.getInstance().getResources().getString(R.string.lib_team_id);
                //一级代理商编号
                req.oneAgentNo = UserInfo.getUserInfo2SP().getOneAgentNo();
                // 勾选的业务产品id
                req.bpId=bpId;
                req.shareData = shareDatas;//组装分润设置内容
                return stub.addAgentInfo(req);
            }

            @Override
            public void updateUI(Object result, int taskId) {
                dismissProgressDialog();
                if (result == null)
                    return;
                AddAgentProto.AgentAddMsgApi response = (AddAgentProto.AgentAddMsgApi) result;
                if (!TextUtils.isEmpty(response.resMsg.msg))
                    showToast(response.resMsg.msg);
                if (!response.resMsg.status)
                    return;

                AllUtils.addActivity(AgentAddStep4.this);
                SPUtils.removeHistory(Constant.KEY.AGENT_ADD_INFO);
                AllUtils.finishActivity();
                finish();
            }
        });
    }

}
